﻿using DataAccess.Dal;
using DataAccess.Enums;
using DataAccess.FrameWork;
using DataAccess.Model;
using DataAccess.Model.Entities;
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System.Linq;

namespace DataAccess.ModelT4
{
    /// <summary>
    /// 数据库连接服务
    /// </summary>
    public class MySqlConnectionService
    {
        private string connectionStr = string.Empty;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connStr"></param>
        public MySqlConnectionService(string connStr)
        {
            connectionStr = connStr;
        }

        /// <summary>
        /// 获取数据表明细
        /// </summary>
        /// <param name="dbName">库名</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public TableModel GetTableDetail(string dbName, string tableName)
        {
            TableModel result = new TableModel();
            var table = GetTable(dbName, tableName);
            result.TableName = table.TableName;
            result.DbName = table.DbName;
            result.TableDes = table.TableDes;
            var fields = GetTableField(dbName, tableName);
            result.SetFileds(fields);
            return result;
        }

        /// <summary>
        /// 获取表信息
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private TableEntity GetTable(string dbName, string tableName)
        {
            TableEntity table = null;
            var param = new Dictionary<string, object>();
            param.Add("DbName", dbName);
            param.Add("TableName", tableName);
            var tables = DBHelper.SelectList<TableEntity>(new FrameWorkItem
            {
                Sql = DataBaseDal.GetTableDetail(),
                ConnectionString = connectionStr,
                SqlParam = param,
            }, DBType.MYSQL, true);
            if (tables != null && tables.Count > 0)
            {
                table = tables.First();
            }
            return table;
        }

        /// <summary>
        /// 获取字段信息
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private List<FieldEntity> GetTableField(string dbName, string tableName)
        {

            var param = new Dictionary<string, object>();
            param.Add("DbName", dbName);
            param.Add("TableName", tableName);
            return DBHelper.SelectList<FieldEntity>(new FrameWorkItem
            {
                Sql = DataBaseDal.GetTableFieldsDetail(),
                ConnectionString = connectionStr,
                SqlParam = param,
            }, DBType.MYSQL, true);
        }
    }
}
